/*
 * @Author: 钱合明
 * @Date: 2022-05-23 15:04:09
 * @LastEditors: 钱合明
 * @LastEditTime: 2022-08-11 10:09:50
 * @FilePath: \dengta-frontend-project\frontend\src\store\modules\chatwebsocket\modules\wechat.js
 * @Description: wesocket
 * 18156516639
 * Copyright (c) 2022 by 钱合明, All Rights Reserved.
 */
import Datastore from 'nedb';
import Vue from 'vue';
import base64 from '@/libs/base64.js';
// import * as $websocket from '@/plugins/request/chatwebsocket';
// import dayjs from 'dayjs';
// import {commit} from "lodash/seq";
import { WechatFriendList } from '@api/chat';
let db;
db = Vue.prototype.$db = new Datastore({ filename: './db/chat.db', autoload: true });
/**
 * 用户信息
 * */
export default {
    namespaced: true,
    state: {
        // websocket链接状态
        websocketLogin: false,
        // 用户信息
        chatListObj: {},
        // 如果10s没返回数据，则认为推送数据结束
        timeout: 10000,
        // 删除和插入数据的时间句柄
        timeHandler: null,
        // 当前选中的会话ID
        currentConversationId: '',
        // 当前选择的归属人
        realname: '',
        // 当前单击微信获取的信息
        covItem: {},
        // 当前展示所有的会话列表
        currentChatConversation: [],
        // 搜索结果
        searchChatConversation: [],
        // 搜索关键词
        searchKey: '',
        // 存储当前会话（医生）微信信息
        currentWechat: {},
        // 存储当前会话分组名称
        currentWechatGroupName: '',
        // 存储当前的聊天信息
        chatMessages: [],
        // 存储当前会话（客户）的微信信息
        currentFriend: {},
        // 右侧消息列表的分页
        covPage: 0,
        // 每次获取消息的分页数量
        covLimit: 10,
        // 消息的总数量
        covTotal: 0,
        // 未读消息汇总
        unReadObj: {},
        // 会话处理锁
        loadingLock: false,
        // 页面loading
        conversionLoading: false,
        // 显示搜索结果
        showSearchList: false,
        // 最左侧所有医生的微信列表
        wechatList: [],
        // 大图的模态框
        bigmodal: {},
        // 患者列表数据
        patientList: [],
        // 微信好友信息
        wxFriendInfo: {},
        // 用户保存用户信息
        patientInfo: {},
        // E聊数据
        setEList: [],
        // 微聊回访列表
        returnVisit: [],
        // 需要重置数据库的列表
        needRestoreList: [],
        loadingNum: 0,
        // 点击左侧微信，获取会话的loading
        covListLoading: false,
        showDetail: false
    },
    getters: {
        /**
         * 对会话列表进行过滤&重排序
         * @param {} state 
         * @returns 
         */
        filterCurrentChatConversation(state) {
            let data = state.currentChatConversation.filter(item => {
                return item.UserName.indexOf('@chatroom') < 0 && item.UserName !== 'weixin' && item.UserName !== 'sos_helper' && item.friend_info.friendid;
            });
            // 对会话进行排序，先根据置顶排序，然后根据时间排序
            data.sort((a, b) => {
                if (a.IsTop && !b.IsTop) {
                    return -1;
                } else if (!a.IsTop && b.IsTop) {
                    return 1;
                } else {
                    return b.UpdateTime - a.UpdateTime;
                }
            });
            return data;
        },
        // 对消息进行重排序
        allMessages(state) {
            return state.chatMessages.sort((a, b) => {
                return new Date(a.create_time).getTime() - new Date(b.create_time).getTime();
            });
        },
        // 获取查看大图
        getbigmodal(state) {
            return state.bigmodal;
        },
    },
    mutations: {
        setWebsocketLogin(state, payload) {
            state.websocketLogin = payload;
        },
        setCurrentConversationId(state, payload) {
            state.currentConversationId = payload;
            localStorage.setItem('currentConversationId', payload);
        },
        setRealname(state,payload){
            state.realname = payload;
        },
        setcovItem(state,payload){
            state.covItem = payload;
        },
        SET_CURRENT_CONVERS(state, payload) {
            state.currentChatConversation = payload;
        },
        SET_SEARCH_CURRENT_CONVERS(state, payload) {
            state.searchChatConversation = payload;
        },
        SET_SEARCH_KEY(state, payload) {
            state.searchKey = payload;
        },
        clearnChatMessages(state) {
            state.chatMessages = [];
        },
        // 设置聊天内容
        SET_WECHATRECORD(state, data) {
            state.covTotalPage = Math.ceil(data.total / state.covLimit);
            let chatMessagesIds = state.chatMessages.map(i => {
                return i.msgSvrId;
            });
            data.list.forEach(i => {
                if (!chatMessagesIds.includes(i.msgSvrId)) {
                    state.chatMessages.push(i);
                }
            });
        },
        setCurrentFriend(state, payload) {
            state.currentFriend = payload;
        },
        setCovPage(state, page) {
            state.covPage = page;
        },
        // 好友来消息更新会话【未读数】
        updateMessageContentAndTime(state, obj) {
            // 非选中好友会话才去更新未读数和总数
            if (state.currentConversationId === obj.WeChatId && state.currentFriend.friendid !== obj.FriendId) {
                // 1.好友未读数+1
                state.currentChatConversation.map(item => {
                    item.child.map(childItem => {
                        if (childItem.friendid === obj.FriendId) {
                            childItem.unread_cnt = parseInt(childItem.unread_cnt) + 1;
                        }
                        return childItem;
                    });
                    return item;
                });

                // 2.微信总数+1
                let copyUnReadObj = JSON.parse(JSON.stringify(state.unReadObj));
                state.unReadObj[state.currentConversationId] = copyUnReadObj[state.currentConversationId]
                    ? copyUnReadObj[state.currentConversationId] + 1
                    : 1;
            }
        },
        // 主动发送消息更新会话
        /*updateSendedContentAndTime(state, obj) {

        },*/
        setWechatList(state, payload) {
            let list = payload.sort((a, b) => {
                return a.isonline - b.isonline;
            });
            state.wechatList = list;
        },
        SET_DETAILTASK(state, list) {
            state.bigmodal = {
                MsgId: list.MsgId,
                Content: base64.b64DecodeUnicode(list.Content)
            };
            state.chatMessages.forEach(item => {
                if (item.msgSvrId === list.MsgId) {
                    item.Contents = base64.b64DecodeUnicode(list.Content);
                }
            });
        },
        SET_CURRENT_WECHAT(state, obj) {
            state.currentWechat = obj;
            localStorage.setItem('currentWechat', JSON.stringify(obj));
        },
        SET_CURRENT_WECHAT_GROUP_NAME(state, payload) {
            state.currentWechatGroupName = payload;
        },
        setPatientList(state, list) {
            state.patientList = list;
        },
        setWxFriendInfo(state, obj) {
            state.wxFriendInfo = obj;
        },
        setReturnVisit(state, obj) {
            state.returnVisit = obj;
        },
        setLoadingLock(state, payload) {
            state.loadingLock = payload;
        },
        setConversionLoading(state, payload) {
            state.conversionLoading = payload;
        },
        setShowSearchList(state, payload) {
            state.showSearchList = payload;
        },
        /**
         * 下线通知
         */
        wechatOffline(state, wxId) {
            let index = state.wechatList.findIndex(item => {
                return item.wechatid === wxId;
            });
            let result = state.wechatList[index];
            result.isonline = '1';
            state.wechatList.splice(index, 1, result);
        },
        // 修改
        setPatientInfo(state, patientInfo) {
            state.patientInfo = patientInfo;
        },
        // 设置右侧detail
        setShowDetail (state, payload) {
            state.showDetail = payload;
        },
        SET_INIT_WEILIAO_DATA(state, payload) {
            // 选中个微信ID
            let currentConversationId = localStorage.getItem('currentConversationId');
            state.currentConversationId = currentConversationId ? currentConversationId : '';
            // 选中微信
            let currentWechat = localStorage.getItem('currentWechat');
            state.currentWechat = JSON.parse(currentWechat);
        },
    },
    actions: {
        // 通知会话更新完成
        setFriendList({ state, commit, dispatch }, payload) {
            let data = JSON.parse(payload.message);
            WechatFriendList({wechat_id: data.WeChatId}).then(res => {
                setTimeout(() => {
                    state.conversionLoading = false;
                }, 500);
                dispatch('setCurrentCoversation', res.list);
            }).catch(error => {
                state.conversionLoading = false;
            });
        },
        // 设置当前会话
        setCurrentCoversation({ state, commit, dispatch }, payload) {
            commit('SET_CURRENT_CONVERS', payload);
            dispatch('getUnreadMessage');
        },
        // 设置当前选中微信信息
        setCurrentWechat({ state, commit, dispatch }, payload) {
            commit('SET_CURRENT_WECHAT', payload);
        },
        // 搜索好友
        setSearchCoversation({ state, commit, dispatch }, payload) {
            commit('SET_SEARCH_CURRENT_CONVERS', payload);
        },
        // 搜索好友
        setSearchKey({ state, commit, dispatch }, payload) {
            commit('SET_SEARCH_KEY', payload);
        },
        // 设置聊天信息列表
        setWechatRecord({ state, commit, dispatch }, payload) {
            let list = JSON.parse(payload.message);
            commit('SET_WECHATRECORD', list);
        },
        // 手机操作已读清空未读
        conversionReaded({ state, commit, dispatch }, payload) {
            // {"msgType":"PostMessageReadNotice","accessToken":null,"refMsgId":1035,"message":"{\"WeChatId\":\"wxid_a3dsp4ivqnwb22\",\"FriendId\":\"wxid_y83pgimdeq7y21\"}"}
            let data = JSON.parse(payload.message);

            // 1.清空当前好友未读数据
            let needMinusNum = 0;
            state.currentChatConversation = state.currentChatConversation.map(item => {
                if (item.friendid === data.FriendId) {
                    needMinusNum = item.unread_cnt;
                    item.unread_cnt = 0;
                }
                return item;
            });

            // 2.更新微信总未读数
            let unReadObj = JSON.parse(JSON.stringify(state.unReadObj));
            unReadObj[data.WeChatId] = unReadObj[data.WeChatId] - needMinusNum <= 0 ? 0 : unReadObj[data.WeChatId] - needMinusNum;
            state.unReadObj = unReadObj;
        },
        // 主动点击好友标为已读
        webConversionReaded({ state, commit, dispatch }, payload) {
            // 1.清空当前好友未读数据
            let unreadCnt = 0;
            state.currentChatConversation.map(item => {
                item.child.map(childItem => {
                    if (childItem.friendid === payload.friendid) {
                        unreadCnt = childItem.unread_cnt;
                        childItem.unread_cnt = 0;
                    }
                    return childItem;
                });
                return item;
            });

            // 2.更新微信总未读数
            let unReadObj = JSON.parse(JSON.stringify(state.unReadObj));
            if (unReadObj[state.currentConversationId]) {
                let total = unReadObj[state.currentConversationId] - unreadCnt;
                unReadObj[state.currentConversationId] = total <= 0 ? 0 : total;
                state.unReadObj = unReadObj;
            }
        },
        // 获取选中微信的未读消息
        getUnreadMessage({ state, commit, dispatch }, payload) {
            let unReadObj = {};
            if (state.currentConversationId) {
                let total = 0;
                state.currentChatConversation.forEach(item => {
                    item.child.forEach(childItem => {
                        total += parseInt(childItem.unread_cnt);
                    });
                });
                unReadObj[state.currentConversationId] = total;
            }
            state.unReadObj = unReadObj;
        },
        setDetailTask({ commit }, DetailTask) {
            let list = JSON.parse(DetailTask.message);
            commit('SET_DETAILTASK', list);
        },
        /**
         * 上线通知
         */
        online({ state, commit, dispatch }, message) {
            // 更新微信列表
            let index = state.wechatList.findIndex(item => {
                return item.wechatid === message.WeChatId;
            });
            let result = state.wechatList[index];
            result.isonline = '0';
            state.wechatList.splice(index, 1, result);
        },
        /**
         * 任务结果通知
         */
        taskResultNotice({ state, commit, dispatch }, payload) {
            let data = JSON.parse(payload.message);
            switch (data.TaskType) {
                case 'ChatRoomActionTask':
                    // 置顶or取消置顶
                    if (data.Success && data.action !== undefined && data.action === 16) {
                        dispatch('setFriendList', payload);
                    }
                    break;
                default:
                    break;
            }
        },
        // 设置当前选中的微信分组
        setCurrentWechatGroupName({ state, commit, dispatch }, payload) {
            commit('SET_CURRENT_WECHAT_GROUP_NAME', payload);
        },
        // 清空微聊缓存
        // 初始化数据
        initWeiliaoData({ state, commit, dispatch }, payload) {
            commit('SET_INIT_WEILIAO_DATA', payload);
        },
    }
};
